package com.santoker.user.service.config;

import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Component
@EnableOpenApi
public class SwaggerConfig {

    @Autowired
    private ConfigProperty configProperty;

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.OAS_30)
                .enable(configProperty.swaggerEnable)
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
//                .globalRequestParameters(globalRequestParameters)
                .securitySchemes(securitySchemes()) //添加token
                .securityContexts(securityContexts()) //swagger配置页面访问是否需要传token
                .apiInfo(apiInfo());
    }


    private ApiInfo apiInfo() {
        StringBuilder sb = new StringBuilder();
        return new ApiInfoBuilder()
                .title("用户服务接口文档")
                .version("lastVersion")
                .description(sb.toString())
                .build();
    }

    private List<SecurityScheme> securitySchemes() {
        return Collections.singletonList(new ApiKey("token", "token", "header"));
    }

    private List<SecurityContext> securityContexts() {
        List<SecurityContext> securityContexts = new ArrayList<>();
        securityContexts.add(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        // 过滤不需要token的请求
                        //.forPaths(PathSelectors.regex("^(?!auth).*$"))
                        .build());
        return securityContexts;
    }

    List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        List<SecurityReference> securityReferences = new ArrayList<>();
        securityReferences.add(new SecurityReference("token", new AuthorizationScope[]{authorizationScope}));
        return securityReferences;
    }

}